package com.vfa.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import api.wireless.gdata.client.AbstructParserFactory;
import api.wireless.gdata.client.ServiceDataClient;
import api.wireless.gdata.data.Feed;
import api.wireless.gdata.docs.client.DocsClient;
import api.wireless.gdata.docs.client.DocsGDataClient;
import api.wireless.gdata.docs.data.DocumentEntry;
import api.wireless.gdata.docs.parser.xml.XmlDocsGDataParserFactory;
import api.wireless.gdata.parser.ParseException;
import api.wireless.gdata.spreadsheets.client.SpreadsheetGDataClient;
import api.wireless.gdata.spreadsheets.client.SpreadsheetsClient;
import api.wireless.gdata.spreadsheets.data.SpreadsheetEntry;
import api.wireless.gdata.spreadsheets.parser.xml.XmlSpreadsheetsGDataParserFactory;
import api.wireless.gdata.util.AuthenticationException;
import api.wireless.gdata.util.ContentType;
import api.wireless.gdata.util.ServiceException;

public class SyncDocs{
	
	private static final String USER_EMAIL = "email";
	private static final String USER_PASS = "pass";
	private static DocsClient docsClient;
	private static Boolean isAuthorize = false;
	private String Email, Pass;
	public SyncDocs(Context context){
		this.context = context;
		LoadAutho();
		
		System.out.println(Email);
		System.out.println(Pass);
	}
	public SyncDocs(){
		//LoadAutho();
		//System.out.println(Email);
		//System.out.println(Pass);
	}
	private static SyncDocs Instance;
	public static SyncDocs getIntance(){
		if(Instance==null)
			Instance = new SyncDocs();
		return Instance;
	}
	public boolean Autho(String EMAIL, String PASS){
		DocsGDataClient dataclient = new DocsGDataClient("test",
    			ServiceDataClient.DEFAULT_AUTH_PROTOCOL,
    			ServiceDataClient.DEFAULT_HOST);
        this.Email = EMAIL;
        this.Pass = PASS;
    	docsClient = new DocsClient(dataclient,new XmlDocsGDataParserFactory(new AbstructParserFactory()));
    		
    	try {
			docsClient.setUserCredentials(EMAIL, PASS);
			isAuthorize = true;
			saveAutho();
			return true;
		} catch (AuthenticationException e) {
					isAuthorize = false;
					
			e.printStackTrace();
			return false;
		}
		
	}
	
	public ArrayList<Entry> getSpreadEntry() {
		Feed<DocumentEntry> feed;
		ArrayList<Entry> rs = new ArrayList<Entry>();
		try {
			feed = docsClient.getFeedOf("spreadsheets");

			for (DocumentEntry entry : feed.getEntries()) {
				Entry temp = new Entry(entry.getId(), entry.getTitle(),
						entry.getUpdateDate());
				rs.add(temp);

			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		return rs;
	}
	
	
	public String downloadSpread(String entryid) throws ParseException, IOException, ServiceException {
		SpreadsheetGDataClient sdataclient = new SpreadsheetGDataClient("test",
				ServiceDataClient.DEFAULT_AUTH_PROTOCOL,
				SpreadsheetsClient.SPREADSHEETS_HOST);

		SpreadsheetsClient spread_client = new SpreadsheetsClient(sdataclient,
				new XmlSpreadsheetsGDataParserFactory(
						new AbstructParserFactory()));
		try {
			docsClient.setUserCredentials(Email, Pass);
			spread_client.setUserCredentials(Email, Pass);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String token1 = docsClient.getToken();
		String token2 = spread_client.getToken();

		docsClient.setToken(token2);

		InputStream istr = null;
		boolean success = false;
		String path;

				istr = docsClient.getMediaEntry_my(entryid,
						docsClient.getToken(), ContentType.CSV);
				File sdcardFolder = Environment.getExternalStorageDirectory();
				path = sdcardFolder+"/temp.csv";
				success = downloadFile(istr, path);
				if(success==true)
				{
					return path;
				}
				else{
					return "";
				}

	}

	public boolean downloadFile(InputStream inputStream, String pathFile) throws IOException {
			File file = new File(pathFile);
			// File file = new File("/sdcard/"+newFileName, newFileName);
			FileOutputStream fileOutput = new FileOutputStream(file);
			int downloadedSize = 0;
			byte[] buffer = new byte[1024];
			int bufferLength = 0;
			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
			}
			fileOutput.close();
			return true;


	}

	public DocumentEntry returnEntry(String filename){
		Feed<DocumentEntry> feed;
		DocumentEntry entryget = null;
		try {
			feed = docsClient.getFeedOf("spreadsheets");
			
			for(DocumentEntry entry : feed.getEntries()){
				if (entry.getTitle().equals(filename)) {
					System.out.println(""+entry.getTitle()+" ==== "+ entry.getEditUri() + " \n media uri  "+ entry.getEditMediaUri());
					entryget = entry;    				
    				System.out.println("co entry ");
    				break;
				}
				else{
					DocumentEntry createentry = new DocumentEntry();
        			createentry.setSpreadsheet();
        			createentry.setTitle(filename);
        			docsClient.createDocument(createentry);
        			System.out.println("create thanh cong");
        			
        			
        			//Autho(Email, Pass);
        			feed = docsClient.getFeedOf("spreadsheets");
        			for(DocumentEntry newentry : feed.getEntries()){
        				System.out.println("entry.getTitle() = "+newentry.getTitle());
        				if (newentry.getTitle().equals(filename)) {
        					entryget=newentry;
        					
        					break;
        				}
        				
        			}
        			
        			//entryget = returnEntry(filename);
        			System.out.println("entryget.getEditUri(); = "+entryget.getEditUri());
        			break;
				}
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return entryget;
	}
	
	public void UpdateToGoogleDocs( File filepath, String filename){
		
		UpdateEntry(returnEntry(filename), filepath);
		
	}
	private void UpdateEntry(DocumentEntry entry, File filepath){
		String uripath;
		URL url;
		FileInputStream inputStream ;
		try {
			uripath = entry.getEditMediaUri();
			url = new URL(uripath);
			inputStream = new FileInputStream(filepath);
			docsClient.updateMediaEntry(url, docsClient.getToken(), inputStream, ContentType.CSV);
			System.out.println("dong bo voi google thanh cong !");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//end update
	}
	
	public Boolean isAuthorize() {
		return isAuthorize;
	}
	
	private SharedPreferences sharePre;
	private Context context;
	public void setContext(Context context) {
		this.context = context;
	}
	private Editor edit;
	
	public void saveAutho(){
		sharePre = context.getSharedPreferences("InsertQuestion", context.MODE_PRIVATE);
		edit = sharePre.edit();
		edit.putString(USER_EMAIL, Email);
		edit.putString(USER_PASS, Pass);
		edit.commit();
	}
	public boolean LoadAutho(){
		SharedPreferences sharedPreferences = context.getSharedPreferences("InsertQuestion", context.MODE_PRIVATE);
		//sharedPreferences.registerOnSharedPreferenceChangeListener(this);
		Email = sharedPreferences.getString(USER_EMAIL, "");
		Pass = sharedPreferences.getString(USER_PASS, "");
		return Autho(Email, Pass);

	}

}
